package TwitterCrawler;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import javax.swing.text.DateFormatter;

import org.json.*;

import HibernateMapping.*;

public class Main {
	private static final String twitterSearchURL = "http://search.twitter.com/search.json?q=";

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		List<Keyword> keywords = Keyword.getKeywords();

		for (int i = 0; i < keywords.size(); i++) {
			String result = "";
			try {
				if (keywords.get(i).getText().isEmpty()) {
					continue;
				}

				if (keywords.get(i).getMax_id().equals("-1")) {
					result = getPageContent(Main.twitterSearchURL
							+ keywords.get(i).getText());
				} else {
					result = getPageContent(Main.twitterSearchURL
							+ keywords.get(i).getText() + "&since_id="
							+ keywords.get(i).getMax_id());
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();

				continue;
			}

			try {
				JSONObject parseResult = new JSONObject(result);

				String max_id = parseResult.getString("max_id_str");

				JSONArray parseTweets = parseResult.getJSONArray("results");

				for (int j = 0; j < parseTweets.length(); j++) {
					JSONObject parseTweet = parseTweets.getJSONObject(j);
					String tweetText = parseTweet.getString("text");
					String idUser = parseTweet.getString("from_user_id_str");
					String userName = parseTweet.getString("from_user");
					String dateParse = parseTweet.getString("created_at");
					// System.out.println(dateParse);

					SimpleDateFormat formatter = new SimpleDateFormat(
							"E, dd MMM yyyy HH:mm:ss Z", Locale.ENGLISH);
					Date date = new Date();
					try {
						date = (Date) formatter.parse(dateParse);
					} catch (ParseException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
					User currentUser = User.getUser(idUser, userName);
					Tweet.addTweet(tweetText, date, -1, currentUser, keywords.get(i));
				}
				
				keywords.get(i).setMax_id(max_id);
				Keyword.updateMaxID(keywords.get(i));
				
				try {
					Thread.sleep(400);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public static String getPageContent(String givenUrl) throws IOException {
		URL url = new URL(givenUrl);

		URLConnection uc = url.openConnection();
		StringBuffer sb = new StringBuffer();
		String pageContent = "";

		InputStream is = uc.getInputStream();
		int ch;

		while ((ch = is.read()) != -1) {
			sb.append((char) ch);
		}

		pageContent = sb.toString();
		is.close();
		is = null;
		sb = null;

		return pageContent;
	}

}
